package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import com.xuecheng.ucenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class UserServiceImpl extends ServiceImpl<XcUserMapper,XcUser> implements UserDetailsService, UserService {

    @Autowired
    XcUserMapper xcUserMapper ;

    @Autowired
    XcMenuMapper xcMenuMapper ;

    @Autowired
    ApplicationContext applicationContext ;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null ;
        try{
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        }catch (Exception e){
            throw new RuntimeException("请求认证参数不符合要求");
        }
        //认证类型，有password，wx
        String authType = authParamsDto.getAuthType();

        String beanName = authType+"_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        XcUserExt execute = authService.execute(authParamsDto);
        UserDetails userPrincipal = getUserPrincipal(execute);
        return userPrincipal;
    }

    public UserDetails getUserPrincipal(XcUserExt execute){
        String password = execute.getPassword();
        //根据用户 id 查询权限
        String[] authorities = {"test"};
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(execute.getId());
        if(xcMenus.size()>0){
            ArrayList<String> permission = new ArrayList<>();
            xcMenus.forEach(m->{
                permission.add(m.getCode());
            });
            authorities = permission.toArray(new String[0]);

        }
        execute.setPassword(null);
        String userJson = JSON.toJSONString(execute);

        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails ;
    }
}
